package com.ericdm.callingandsmsstatistics;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.ContactsContract;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class PhoneDetailInfoActivity extends Activity {
	String phoneNumber = "";
	String tableName = "";
	String columnName = "";
	String startTime = "";
	String endTime = "";	
	private TextView showPhoneNumber = null;
	private ListView listVieePhoneDetail = null;
	private MyHanlder myHandler;
	List<HashMap<String, String>> list_ = new ArrayList<HashMap<String, String>>();
	private static ProgressDialog dialog;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_phone_detail_info);
		Bundle bundle = this.getIntent().getExtras();
		phoneNumber = bundle.getString("phoneNumber");
		tableName = bundle.getString("tableName");
		startTime = bundle.getString("startTime");
		endTime = bundle.getString("endTime");
		showPhoneNumber = (TextView) findViewById(R.id.showPhoneNumber);
		showPhoneNumber.setText(getContactNameByPhonenumber(phoneNumber) + ":");
		showPhoneNumber.setTextColor(android.graphics.Color.MAGENTA);

		dialog = new ProgressDialog(PhoneDetailInfoActivity.this); 
		dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); 
		dialog.setTitle("检索数据"); 
		dialog.setMessage("数据查询中，请稍后");
		dialog.setIcon(android.R.drawable.ic_dialog_map);
		dialog.show(); 
		
		listVieePhoneDetail = (ListView) findViewById(R.id.listViewPhoneDetailInfo);
		ExitApplication.getInstance().addActivity(this);
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		myHandler = new MyHanlder();
		QueryDetailDataThread queryDetailDataThread = new QueryDetailDataThread();
		new Thread(queryDetailDataThread).start();
	}

	@SuppressLint("HandlerLeak")
	class MyHanlder extends Handler
	{
		public MyHanlder() {	
		}

		@SuppressWarnings("unchecked")
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			Bundle bundle = msg.getData();
			List<HashMap<String, String>> detaliList_ = new ArrayList<HashMap<String, String>>();
			detaliList_ =  (List<HashMap<String, String>>) bundle.getSerializable("detailInfo");
			setListViewData(detaliList_);	
			dialog.cancel();
		}
	}
	
	public void setListViewData(List<HashMap<String, String>> thelist)
	{
		listVieePhoneDetail.setAdapter(new SimpleAdapter(this, thelist , R.layout.listviewdetail, new String[] { "record" }, new int[] {  R.id.listViewdetal }));
	}
		
	public List<HashMap<String, String>> getdetailData()
	{
		List<HashMap<String, String>> theList = new ArrayList<HashMap<String, String>>();
		DatabaseHelper databaseHelper = new DatabaseHelper(MainApplication.getContext(), "CallingHistoryDatabase");
		SQLiteDatabase sqLiteDatabase = databaseHelper.getReadableDatabase();
		if (tableName.equals(DatabaseOperator.TABLE_NAME_OUGGOINGCALL)) {
			columnName = "OUT_GOING_CALL";
		}
		if (tableName.equals(DatabaseOperator.TABLE_NAME_INCOMINGCALL)) {
			columnName = "INCOMMING_CALL";
		}	
		if (tableName.equals(DatabaseOperator.TABLE_NAME_RECEVIEDSMS)) {
			columnName = "RECEVIED_SMS";
		}	
		if (tableName.equals(DatabaseOperator.TABLE_NAME_SENDEDSMS)) {
			columnName = "SENDED_SMS";
		}	
		Cursor cursor = sqLiteDatabase.query(tableName, new String[] { "PHONENUMBER", columnName, "DATE_", "DATEFULL"}, "PHONENUMBER=?", new String[] { phoneNumber }, null, null, null);
		while (cursor.moveToNext()) 
		{
			String date = cursor.getString(cursor.getColumnIndex("DATE_"));
			if ((date.compareTo(startTime) >= 0) && (date.compareTo(endTime) <= 0))
			{
				HashMap<String, String> hashMap = new HashMap<String, String>();
				String queryedData = cursor.getString(cursor.getColumnIndex(columnName));
				String date_ = cursor.getString(cursor.getColumnIndex("DATEFULL"));
				if (tableName.equals(DatabaseOperator.TABLE_NAME_OUGGOINGCALL) || tableName.equals(DatabaseOperator.TABLE_NAME_INCOMINGCALL)) {
					hashMap.put("record", date_ + " : " + MainActivity.secondToMinutes(Integer.parseInt(queryedData)));
					theList.add(hashMap);
				}
				else {
					hashMap.put("record", date_);
					theList.add(hashMap);
				}
			}
		}
		cursor.close();
		sqLiteDatabase.close();
		return theList;
	}
	
	class QueryDetailDataThread implements Runnable
	{
		List<HashMap<String, String>> detailList = new ArrayList<HashMap<String, String>>();
		@Override
		public void run() {
			// TODO Auto-generated method stub
			Message msg = new Message();
			Bundle bundle = new Bundle();
			detailList = getdetailData();
			bundle.putSerializable("detailInfo", (Serializable)detailList);
			msg.setData(bundle);
			PhoneDetailInfoActivity.this.myHandler.sendMessage(msg);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.phone_detail_info, menu);
		return true;
	}
	
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId())
		{
			case R.id.action_settings:
				ExitApplication.getInstance().exit(); 
				break;
			default:
				break;
		}
		return super.onOptionsItemSelected(item);
	}
	
	public String getContactNameByPhonenumber(String phonenumber)
	{
		String name = "";
		String phoneNumber_ = phonenumber.replace(" ", "");
		String[] projection = { ContactsContract.PhoneLookup.DISPLAY_NAME,  ContactsContract.CommonDataKinds.Phone.NUMBER};  
		Cursor cursor = this.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection, null,null, null); 
		if( cursor == null ){
			return phonenumber;
		}
		for( int i = 0; i < cursor.getCount(); i++ )
		{
			cursor.moveToPosition(i);
			int phoneFieldColumnIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
			String number_ = cursor.getString(phoneFieldColumnIndex);
			if (number_.replace(" ", "").equals(phoneNumber_)) {
				int nameFieldColumnIndex = cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME);
				name = cursor.getString(nameFieldColumnIndex);
				return name;
			}
		}
		return phonenumber;
	}
}
